<template>
  <div>
    <h1>倾听器：</h1>
    <h2>示例一、字符串监听</h2>
    <span>商品名称：</span>
    <el-input v-model="name" placeholder="请输入内容"></el-input>
    <span>商品数量：{{count}}</span>

    <h2>示例二、数字监听</h2>
    <span>商品数量：</span>
    <el-input v-model="count" placeholder="请输入内容"></el-input>
    <span>商品数量是否大小10：{{isMax}}</span>

    <h2>示例三、布尔值监听</h2>
    <span>布尔值：</span>
    <el-select v-model="isMax" placeholder="请选择">
      <el-option key="true" label="true" :value=true> </el-option>
      <el-option key="false" label="false" :value=false></el-option>
    </el-select>
    <span>{{message}}</span>

    <h2>示例四、数组监听</h2>
    <span>添加数组：</span>
    <el-button type="primary" @click="add()">添加数组</el-button>

    <h2>示例五、倾听对象某属性的变化</h2>
    <span>商品名：</span>
    <el-input v-model="product.name" placeholder="请输入内容"></el-input>

    <h2>示例六、handler方法</h2>
    <span>商品名称：</span>
    <el-input v-model="nameOne" placeholder="请输入内容"></el-input>
    <span>商品数量：{{countOne}}</span>

    <h2>示例八、deep属性</h2>
    <div>商品名称：
      <el-input v-model="product.name" />
    </div>
    <div>商品数量：
      <el-input v-model="product.count" />
    </div>
    <div>商品标题：
      <el-input v-model="product.title" />
    </div>

  </div>

</template>

<script>
export default {
  name: 'watch',
  data () {
    return {
      msg: '倾听器',

      name: '商品',
      count: 9,

      isMax: false,
      message: '',
      list: [],

      product: {
        name: '',
        count: '',
        title: ''
      },

      nameOne: '商品',
      countOne: 9,
    }
  },
  methods: {

    add () {
      this.list.push({
        name: this.name,
        count: this.count
      })
    }

  },

  watch: {
    name: function () {
      this.count = this.count + 1
    },

    count: function (newVal, oldVal) {
      if (newVal > 10) {
        this.isMax = true
      }
      if (newVal < 10) {
        this.isMax = false
      }

    },

    isMax: function (newVal) {
      if (newVal) {
        this.message = '注意：您购买的数量较大，请确认是否操作有误'
      } else {
        this.message = '注意：您购买的数量较小，请确认是否操作有误'
      }
    },

    list () {
      console.log('数据发生改变')
    },

    'product.name': function (newValue) {
      console.log(newValue)
    },

    nameOne: {
      handler (newVal, oldVal) {
        this.countOne = this.countOne + 1
        console.log(newVal)
      },

      // 代表在wacth里声明了name这个方法之后立即先去执行一次handler方法
      immediate: true
    },

    product: {
      handler: function (newVal) {
        console.log(newVal)
      },
      deep: true
    }


  },


}
</script>
<style scoped>
</style>
